import Vue from 'vue'
import Vuex from 'vuex'
import {getToken, removeToken, setToken} from "@/utils/auth";
import {getLoginInfo, login, logout} from "@/api/user";

Vue.use(Vuex)


const store = new Vuex.Store({
    state: {
        token: getToken(),
        name: ''
    },
    // 调用远程API获取数据
    actions: {
        login({commit}, userInfo) {
            const {account, password} = userInfo
            return new Promise((resolve, reject) => {
                login({account: account.trim(), password: password.trim()}).then(response => {
                    // 取出真实的数据
                    const data = response.data
                    // 登录成功后将token存入store中的state
                    commit('SET_TOKEN', data.token)
                    //     将token存入cookis
                    setToken(data.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获取用户信息
        getInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getLoginInfo(state.token).then(response => {
                    // 取出真实的数据
                    const data = response.data
                    if (!data) {
                        return reject('验证失败，请重新登录')
                    }
                    const name  = data.realName
                    commit('SET_NAME', name)
                    resolve(data)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 退出登录
        logout({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    removeToken() // must remove  token  first
                    // resetRouter()
                    commit('RESET_STATE')
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 清空 token
        resetToken({ commit }) {
            return new Promise(resolve => {
                removeToken() // must remove  token  first
                commit('RESET_STATE')
                resolve()
            })
        }
    },
    // 直接操作本地存储
    mutations: {
        RESET_STATE: (state) => {
            Object.assign(state, state)
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        }
    }
})

export default store


